<?php
class RCMS_Tools_Tools {

	private static $_allowedWidgets = array(
		'{$page_h1}'
	);


    /**
     * This function did resize image. Type image: gif,png,jpg.
	 *
     * @param <string> $file
     * @param <int> $width
     * @param <int> $height
     * @return <boolean>  true|false
     */
    static public function resizeImage($file, $width, $height, $proportion = true, $fullQuality=false)
    {
        $file = (string) trim($file);
        $width = (integer) $width;
        $height = (integer) $height;
        $proportion = (boolean) $proportion;
		$quality = RCMS_Object_QuickConfig_QuickConfig::$imageQuality;
        $pngQuality = floor((100-$quality)/10);
		/*if($fullQuality){
			$quality = 100;
		}*/

        if($file === '' && $width === 0 && $height === 0) {
            return false;
        }

        if(is_file($file) && file_exists($file)) {
            $fileInfo = getimagesize($file);
            $x = $fileInfo[0];
            $y = $fileInfo[1];
            $fileType = $fileInfo[2];
            $mimeType = $fileInfo['mime'];

            if($proportion === true) {
                $getX_Y = self::calcProportion($x, $y, $width);
                $width = $getX_Y['width'];
                $height = $getX_Y['height'];
            }

            $memoryUseNow = intval(memory_get_usage()/1000000);
            $memoryLimit = intval(ini_get('memory_limit'));
            if (($memoryLimit - $memoryUseNow) < 40) {
                ini_set('memory_limit', ($memoryLimit+40).'M');
            }

            $newImage = imagecreatetruecolor($width, $height);

            switch ($fileType) {
                case 1:
                    $image = imagecreatefromgif($file);
                    break;
                case 2:
                    $image = imagecreatefromjpeg($file);
                    break;
                case 3:
                    $image = imagecreatefrompng($file);
                    break;
                default:
                    return false;
            }
            //transparency fix
            if ($fileType == 1 || $fileType == 3){
                imagealphablending($newImage, false);
                imagesavealpha($newImage, true);
                $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
                imagefilledrectangle($newImage, 0, 0, $width, $height, $transparent);
            }

            imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $x, $y);
			//imagecopyresized($newImage, $image, 0, 0, 0, 0, $width, $height, $x, $y);

            switch ($fileType) {
                case 1:
					imagegif($newImage, $file);
                    break;
                case 2:
					imagejpeg($newImage, $file, $quality);
					break;
                case 3:
					imagepng($newImage, $file, $pngQuality);
                    break;
                default:
                    return false;
            }
            imagedestroy($newImage);
            imagedestroy($image);
            return true;
        }
        return false;
    }

    static public function calcProportion($imgWidth, $imgHeight, $newWidthSize)
    {
        $proportion = array();
		$propPercents = ceil(($imgHeight / $imgWidth) * 100);
		$proportion['width'] = $newWidthSize;
		$proportion['height'] = ceil(($newWidthSize / 100 ) * $propPercents);
		return $proportion;
	}

    static public function cropImage($nw, $nh, $source,$dest) {
		$size = getimagesize($source);
		$w = $size[0];
		$h = $size[1];
		switch($size['mime']) {
			case 'image/gif':
				$simg = imagecreatefromgif($source);
			break;
			case 'image/jpeg':
				$simg = imagecreatefromjpeg($source);
			break;
			case 'image/png':
				$simg = imagecreatefrompng($source);
			break;
		}
		$dimg = imagecreatetruecolor($nw, $nh);
		$wm = $w/$nw;
		$hm = $h/$nh;
		$h_height = $nh/2;
		$w_height = $nw/2;
		if($w> $h) {
			$adjusted_width = $w / $hm;
			$half_width = $adjusted_width / 2;
			$int_width = $half_width - $w_height;
			imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
		}
		elseif(($w <$h) || ($w == $h)) {
			$adjusted_height = $h / $wm;
			$half_height = $adjusted_height / 2;
			$int_height = $half_height - $h_height;
			imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
		}
		else {
			imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
		}
		imagejpeg($dimg,$dest,RCMS_Object_QuickConfig_QuickConfig::$imageQuality);
       // imagejpeg($dimg,100);
	}

    /**
	 * This function generates todays date
	 * @return <date>
	 */
    public static function generateTodaysDateComments()
    {
        return date("F j, Y g:i a");
    }
/**
 * This function generates date to sql format
 * @return <date>
 */
    public static function proccessDateToSqlComments($date)
    {
        $dateArray = explode("-", trim($date));
        $date = date("Y-m-d", mktime(0, 0, 0, $dateArray[0], $dateArray[1],$dateArray[2]));
        return $date;
    }

	/**
	 * This function generates date from sql format
	 * @return <date>
	 */
    public static function proccessPublishingDateCommentsFromSql($date)
    {
            $tmpDateArray  = explode(" ",trim($date));
            $dateArray = explode("-", $tmpDateArray[0]);
            $timeArray = explode(":",$tmpDateArray[1]);
            $date = date("d M Y", mktime($timeArray[0], $timeArray[1], $timeArray[2],  $dateArray[1],$dateArray[2],$dateArray[0]));
            return $date;
    }

    public static function divideStringOnParts($string,$length=50)
    {
     /*   $result ="";
        $partsCount = (int)(strlen($string)/$length);
        for($i=0;$i<$partsCount+1;$i++)
        {
			$result .= substr($string,($i*$length),$i+$length).'<br/>';
			//$result .= substr($string,($i*$length),$i+$length)." ";

        }
        $end = sizeof($result)-6;
        $result = substr($result, 0,$end);
        return $result;*/
		return $string;
    }

	/**
	 * Remove slashes from give value
	 *
	 * @param mixed $value
	 * @return mixed value without slashes
	 */
	public static function stripSlashesIfQuotesOn($value) {
		if(get_magic_quotes_gpc()) {
			return (is_array($value)) ? array_map('self::stripSlashesIfQuotesOn', $value) : stripslashes($value);
		}
		return $value;
	}

	/**
	 * Create concat css file.
	 *
	 * Put all css files in one named concat.css
	 * Mehtod puts files in the specific order wich is:
	 * 1. thickbox.css 2. reset.css 3. style.css 4. content.css 5. ... n. - all other css files sorted alphabeticaly
	 *
	 * @param string $themeName name of the current theme
	 * @return boolean
	 */
	public static function createConcatCss($themeName) {
		$pathToTheme = 'themes/' . $themeName;
		$concatCss = "/* CONCAT.CSS CREATED BY SOTOASTER */\n";
		//adding thickbox.css to concat
		$concatCss .= self::_addCss('system/js/thickbox/', 'thickbox.css');
		//adding reset.css
		$concatCss .= self::_addCss($pathToTheme, 'reset.css');
		//addint style.css
		$concatCss .= self::_addCss($pathToTheme, 'style.css');
		//addint content.css
		$concatCss .= self::_addCss($pathToTheme, 'content.css');

		//all other css files
		$cssFiles = RCMS_Tools_FilesystemTools::findFilesByExt($pathToTheme, 'css');
		sort($cssFiles);
		foreach ($cssFiles as $fileName) {
			if($fileName == 'concat.css' || $fileName == 'style.css' || $fileName == 'content.css' || $fileName == 'reset.css') {
				continue;
			}
			$concatCss .= self::_addCss($pathToTheme, $fileName);
		}
		try {
			RCMS_Tools_FilesystemTools::saveFile($pathToTheme . '/concat.css', $concatCss);
			return true;
		}
		catch (Exception $e) {
			return $e->getMessage();
		}
	}

	/**
	 * Add given css file to common css
	 *
	 * @param string $path
	 * @param string $fileName
	 * @return string
	 */
	private static function _addCss($path, $fileName) {
		//adding css
		$concatCss = '';
		if(file_exists($path . '/' . $fileName)) {
			$concatCss .= "/*" .  strtoupper($fileName) . " start*/\n";
			//get css file contents and remov @charset "utf-8"; string
			$concatCss .= preg_replace('/\@charset\s\"utf-8\"\;/', '', file_get_contents($path . '/' . $fileName));
			$concatCss .= "/*" .  strtoupper($fileName) . " end*/\n";
		}
		return $concatCss;
	}

	/**
	 * Bobble sort for arrays
	 *
	 * @param array $array
	 * @return array sorted array
	 */
	public static function bobbleSort($array) {
		$arraySize = count($array) - 1;
		for($i = $arraySize; $i >= 0; $i--) {
			for($j = 0; $j <= ($i-1); $j++) {
				if($array[$j] < $array[$j+1]) {
					$tmp = $array[$j];
					$array[$j] = $array[$j+1];
					$array[$j+1] = $tmp;
				}
			}
		}
		return $array;
	}

	public static function cryptString($string) {
		$len = strlen($string);
		$cryptedString = '';
		for($len; $len >= 0; $len--) {
			$currChr = ord(substr($string, $len, 1));
			$cryptedString .= '.' . $currChr;
		}
		return ltrim($cryptedString, '.');
	}

	public static function decryptString($string) {
		$decryptedString = '';
		$exploded = explode('.', $string);
		$explodedSize = sizeof($exploded);
		for($explodedSize; $explodedSize > 0; $explodedSize--) {
			if(isset($exploded[$explodedSize]) && $exploded[$explodedSize] != '') {
				$decryptedString .= chr($exploded[$explodedSize]);
			}
		}
		return $decryptedString;
	}

    public static function generateCaptcha() {
	    $sitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
        $captcha = new Zend_Captcha_Image();
		$captcha->setTimeout('300')
			->setWordLen('5')
			->setHeight('60')
			->setFont($sitePath.'system/fonts/Goulong.ttf')
			->setImgDir($sitePath.'tmp');
		$captcha->setFontSize(25);
		$captcha->setDotNoiseLevel(0);
		$captcha->setLineNoiseLevel(0);
		//$captcha->setStartImage();
		$captcha->generate();    //command to generate session + create image
		return $captcha->getId();   //returns the ID given to session &amp; image
    }

	public static function getUserHttpClient() {
		$known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko');
		$pattern = '~(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9]+(?:\.[0-9]+)?)~ui';
		if(!preg_match_all($pattern, strtolower($_SERVER['HTTP_USER_AGENT']), $matches)) {
			return null;
		}
		return $matches['browser'][count($matches['browser'])-1];
	}

	public static function cutWidgets($content) {
		$pattern = '/{\$.+}/Us';
		if(preg_match_all($pattern, $content, $matches)) {
			if(isset($matches[0]) && !empty ($matches[0])) {
				foreach ($matches[0] as $widget) {
					if(!in_array($widget, self::$_allowedWidgets)) {
						$content = str_replace($widget, '', $content);
					}
				}
			}
		}
		return $content;
	}


	public static function convertEncoding($string, $encodingFrom = '', $encodingTo = 'UTF-8') {
		if(!preg_match('//u', $string)) {
			if(!$encodingFrom) {
				if(extension_loaded('mbstring')) {
					$encodingFrom = mb_detect_encoding($string);
				}
				else {
					$encodingFrom = 'ISO-8859-1';
				}
			}
			if(extension_loaded('mbstring')) {
				return mb_convert_encoding($string, $encodingTo, $encodingFrom);
			}
			return iconv($encodingFrom, $encodingTo, $string);
		}
		return $string;
	}
}
